<template>
  <div class="Users-container">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 搜索框 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="Datasheets.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList">
            </el-button>
          </el-input>
        </el-col>

        <el-col :span="4">
          <el-button type="primary" @click="dialogFormVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 点击添加按钮弹出框 -->
      <el-dialog title="请输入内容:" :visible.sync="dialogFormVisible" width="50%" @close="dialogClose">

        <!-- 内容区域 -->
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>

          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password" type="password"></el-input>
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>

          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>


        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 修改用户的对话框 -->
      <el-dialog title="修改用户" :visible.sync="editdialogVisible" width="50%" @close="xiugaidialog">
        <!-- 只要是验证规则肯定是rules结尾 -->
        <!-- 只要是表单的引用肯定是ref结尾的 -->
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
          <el-form-item label="用户名">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>

          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="editdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="edituserinfo">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 用户列表区域 -->
      <el-row>
        <el-table :data="userlist" border>
          <el-table-column type="index"></el-table-column>
          <el-table-column label="姓名" prop="username"></el-table-column>
          <el-table-column label="邮箱" prop="email"></el-table-column>
          <el-table-column label="电话" prop="mobile"></el-table-column>
          <el-table-column label="角色" prop="role_name"></el-table-column>
          <el-table-column label="状态">
            <template slot-scope="scope">
              <!-- {{scope.row}} -->
              <el-switch v-model="scope.row.mg_state" @change="changeState(scope.row)">
              </el-switch>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="240px">

            <template slot-scope="scope">
              <!-- 修改按钮 -->
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="edit_btns(scope.row.id)"></el-button>

              <!-- 删除按钮 -->
              <template>
                <el-button @click="open(scope.row.id)" type="danger" icon="el-icon-delete" size="mini"></el-button>
              </template>

              <el-tooltip content="分配权限" placement="top">
                <el-button type="primary" icon="el-icon-s-tools" size="mini"  @click="setRole(scope.row)"></el-button>
              </el-tooltip>

              <!-- 分配角色弹出框 -->
              <el-dialog title="分配角色" :visible.sync="setdialogVisible" width="50%" @close = "setRoleDialogClose">
                <div>
                  <p>当前的用户：{{userinfo.username}}</p>
                  <p>当前的角色：{{userinfo.role_name}}</p>
                  <p>分配新角色
                      <el-select v-model="selectedRoleId" placeholder="请选择">
                        <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id">
                        </el-option>
                      </el-select>
                  </p>
                </div>
                <span slot="footer" class="dialog-footer">
                  <el-button @click="setdialogVisible = false">取 消</el-button>
                  <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
                </span>
              </el-dialog>

            </template>
          </el-table-column>
        </el-table>
      </el-row>


      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="Datasheets.pagenum" :page-sizes="[2, 3, 5, 10]" :page-size="Datasheets.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>
  </div>
</template>


<script>
  export default {
    data() {
      //验证邮箱
      var cheackEmail = (rule, value, cb) => {
        const regEmail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/

        if (regEmail.test(value)) {
          return cb()
        }
        cb(new Error('请输入合法的邮箱'))
      }
      // 验证手机号
      var cheackMobile = (rule, value, cb) => {
        const regMobile = /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/

        if (regMobile.test(value)) {
          return cb()
        }
        cb(new Error('请输入正确的手机号'))
      }
      return {
        //获取用户列表的参数
        Datasheets: {
          query: '',
          pagenum: 1,
          pagesize: 2
        },

        userlist: [],
        total: 0,

        // 控制弹出框的显示与隐藏
        dialogFormVisible: false,

        // 添加用户的表单数据
        addForm: {
          username: '',
          password: '',
          email: '',
          mobile: ''
        },
        // 添加用户的验证规则
        addFormRules: {
          username: [{
              requied: true,
              message: "请输入用户名",
              trigger: 'blur'
            },
            {
              min: 3,
              max: 10,
              message: '用户名的长度3-10',
              trigger: 'blur'
            }
          ],
          password: [{
              requied: true,
              message: "请输入密码",
              trigger: 'blur'
            },
            {
              min: 6,
              max: 10,
              message: '密码的长度6-10',
              trigger: 'blur'
            }
          ],
          email: [{
            requied: true,
            message: "请输入邮箱",
            trigger: 'blur'
          }, {
            validator: cheackEmail,
            trigger: 'blur'
          }],
          mobile: [{
              requied: true,
              message: "请输入手机号码",
              trigger: 'blur'
            },
            {
              validator: cheackMobile,
              trigger: 'blur'
            },

          ],
        },
        // 控制修改用户对话框的显示与隐藏
        editdialogVisible: false,

        // 查询到的用户信息对象
        editForm: {},

        // 修改表单的验证规则
        editFormRules: {
          email: [{
            requied: true,
            message: "请输入邮箱",
            trigger: 'blur'
          }, ],

          mobile: [{
              requied: true,
              message: "请输入手机号码",
              trigger: 'blur'
            },
            {
              min: 11,
              max: 11,
              message: '请输入11位手机号码',
              trigger: 'blur'
            }
          ],
        },
        // 已选中的角色id
        selectedRoleId:'',

        // 控制分配角色对话框的显示与隐藏
        setdialogVisible: false,
        // 需要被分配角色的用户信息
        userinfo:{},
      // 所有角色的列表数据
        rolesList:[]
      }
    },



    created() {
      this.getUserList()
    },

    methods: {
      async getUserList() {
        const {
          data: res
        } = await this.$http.get('users', {
          params: this.Datasheets
        })

        console.log(res);

        if (res.meta.status !== 200) {
          console.log("获取数据失败");
        } else {
          this.userlist = res.data.users,
            this.total = res.data.total,
            console.log("获取数据成功");
        }
      },

      handleSizeChange(newSize) {
        this.Datasheets.pagesize = newSize
        this.getUserList()
      },
      handleCurrentChange(newPage) {
        this.Datasheets.pagenum = newPage
        this.getUserList()
      },

      // 监听状态的改变
      async changeState(userinfo) {
        const {
          data: res
        } = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)

        if (res.meta.status !== 200) {
          userinfo.mg_state = !userinfo.mg_state
          return this.$message.error('更新用户状态失败')
        }
        this.$message.success('更新用户状态成功')
      },

      clearable() {
        return userlist
      },

      // 关闭表单恢复初始化
      dialogClose() {
        this.$refs.addFormRef.resetFields();
      },
      addUser() {
        this.$refs.addFormRef.validate(async valid => {
          if (!valid) return
          const {
            data: res
          } = await this.$http.post('users', this.addForm)
          if (res.meta.status !== 201) {
            this.$message.error('添加用户失败')
          }
          this.$message.success('添加用户成功')
          this.dialogFormVisible = false
        })
      },

      // 展示编辑对话框
      async edit_btns(id) {
        const {
          data: res
        } = await this.$http.get('users/' + id)

        if (res.meta.status !== 200) {
          return this.$message.error('查询用户失败')
        }
        this.editForm = res.data
        this.editdialogVisible = true

      },

      xiugaidialog() {
        this.$refs.editFormRef.resetFields()
      },
      edituserinfo() {
        this.$refs.editFormRef.validate(async valid => {
          if (valid !== true) {
            return
          }

          const {
            data: res
          } = await this.$http.put('users/' + this.editForm.id, {
            email: this.editForm.email,
            mobile: this.editForm.mobile,
          })
          if (res.meta.status !== 200) {
            return this.$message.error('更新失败')
          } else {
            this.editdialogVisible = false,
              this.getUserList(),
              this.$message.success('更新成功')
          }

        })
      },

      // 删除按钮弹出框
      async open(id) {
        const fanhuizhi = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });

        const {
          data: res
        } = await this.$http.delete('users/' + id)

        if (res.meta.status !== 200) {
          return this.$message.error('')
        }
        this.$message.success('')
        this.getUserList()
      },

    // 展示分配角色的对话框
     async setRole(userinfo){

        this.userinfo = userinfo

     const {data:res} =  await this.$http.get('roles')
      if(res.meta.status !== 200){
        return this.$message.error('获取角色列表失败')
      }


      this.rolesList = res.data
        this.setdialogVisible = true
      },
    

    // 点击按钮分配角色
    async saveRoleInfo(){
      if(!this.selectedRoleId){
         return this.$message.error('请选择要分配的角色')
      }
     

   const {data: res}  =  await this.$http.put(`users/${this.userinfo.id}/role`,
    {rid:this.selectedRoleId})


   if(res.meta.status !== 200){
     return this.$message.error('更新角色失败')
   }    this.$message.success('更新角色成功')
   
        this.getUserList()

        this.setdialogVisible =false


    },

    // 分配角色对话框的关闭事件

    setRoleDialogClose(){
      this.selectedRoleId = '',
      this.userinfo = {}
    }

},
  }
</script>

}
</script>

<style lang="less" scoped>



</style>